import React, { useState, useRef, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { LeftOutline } from 'antd-mobile-icons'
import { Toast } from 'antd-mobile'
import { sendMessage } from '../../api/index'
import { getStoredToken, getStoredUserId, saveChatMessages, loadChatMessages } from '../../utils/localStorageUtils'
import './index.scss'

interface Message {
    id: string
    content: string
    type: number // 1=文本, 2=图片, 3=语音
    isUser: boolean
    timestamp: string
    avatar?: string
}

function Zxun() {
    const navigate = useNavigate()
    const { inquiryId, doctorId, doctorName } = useParams()
    const [messages, setMessages] = useState<Message[]>([])
    const [inputText, setInputText] = useState('')
    const [showEmoji, setShowEmoji] = useState(false)
    const fileInputRef = useRef<HTMLInputElement>(null)
    const messagesEndRef = useRef<HTMLDivElement>(null)

    // 加载保存的消息
    useEffect(() => {
        const savedMessages = loadChatMessages(inquiryId || '1')
        if (savedMessages.length > 0) {
            setMessages(savedMessages)
        } else {
            // 如果没有保存的消息，加载初始消息
            const initialMessages: Message[] = [
                {
                    id: '1',
                    content: '上火吃什么药,藿香正气丸有效吗?',
                    type: 1,
                    isUser: true,
                    timestamp: '上午11:10',
                    avatar: '../../../public/user-avatar.png'
                },
                {
                    id: '2',
                    content: '可以服用藿香正气丸具有解表化湿，理气和中的作用。常用于暑湿感冒,头痛身重胸闷,或恶寒发热，脘腹胀痛，呕吐泄泻。',
                    type: 1,
                    isUser: false,
                    timestamp: '上午11:12',
                    avatar: '../../../public/doctor-avatar.png'
                },
                {
                    id: '3',
                    content: '具体的用法用量是什么呢?',
                    type: 1,
                    isUser: true,
                    timestamp: '下午14:20',
                    avatar: '../../../public/user-avatar.png'
                },
                {
                    id: '4',
                    content: '口服。一次一袋，一日两次。',
                    type: 1,
                    isUser: false,
                    timestamp: '下午14:22',
                    avatar: '../../../public/doctor-avatar.png'
                },
                {
                    id: '5',
                    content: '好的,非常感谢！',
                    type: 1,
                    isUser: true,
                    timestamp: '下午14:25',
                    avatar: '../../../public/user-avatar.png'
                },
                {
                    id: '6',
                    content: '不客气，请问您还有什么需要咨询的吗？',
                    type: 1,
                    isUser: false,
                    timestamp: '下午14:26',
                    avatar: '../../../public/doctor-avatar.png'
                }
            ]
            setMessages(initialMessages)
        }
    }, [inquiryId])

    // 保存消息到localStorage
    useEffect(() => {
        if (messages.length > 0) {
            saveChatMessages(inquiryId || '1', messages)
        }
    }, [messages, inquiryId])

    // 自动滚动到底部
    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
    }, [messages])

    // 发送文本消息
    const sendTextMessage = async () => {
        if (!inputText.trim()) return

        const newMessage: Message = {
            id: Date.now().toString(),
            content: inputText,
            type: 1,
            isUser: true,
            timestamp: new Date().toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            }),
            avatar: '../../../public/user-avatar.png'
        }

        setMessages(prev => [...prev, newMessage])
        setInputText('')

        // 触发自动回复
        sendAutoReply(inputText)

        try {
            const token = getStoredToken()
            const userId = getStoredUserId()

            if (!token || !userId) {
                Toast.show('请先登录')
                return
            }

            await sendMessage(
                parseInt(inquiryId || '1'),
                inputText,
                1, // 文本类型
                parseInt(doctorId || '5')
            )

            Toast.show('消息发送成功！')
        } catch (error) {
            console.error('发送消息失败', error)
            Toast.show('发送失败，请重试！')
        }
    }

    // 发送图片
    const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0]
        if (!file) return

        const reader = new FileReader()
        reader.onload = (e) => {
            const imageUrl = e.target?.result as string
            const newMessage: Message = {
                id: Date.now().toString(),
                content: imageUrl,
                type: 2,
                isUser: true,
                timestamp: new Date().toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                }),
                avatar: '../../../public/user-avatar.png'
            }

            setMessages(prev => [...prev, newMessage])
        }
        reader.readAsDataURL(file)
    }

    // 发送表情
    const sendEmoji = (emoji: string) => {
        const newMessage: Message = {
            id: Date.now().toString(),
            content: emoji,
            type: 1,
            isUser: true,
            timestamp: new Date().toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            }),
            avatar: '../../../public/user-avatar.png'
        }

        setMessages(prev => [...prev, newMessage])
        setShowEmoji(false)
    }

    // 表情列表
    const emojis = ['😊', '😂', '😍', '🤔', '👍', '👎', '❤️', '😢', '😮', '😡', '🎉', '👏']

    // 自动回复函数
    const generateAutoReply = (userMessage: string): string => {
        const message = userMessage.toLowerCase()

        // 根据关键词生成回复
        if (message.includes('药') || message.includes('药物') || message.includes('用药')) {
            const replies = [
                '建议您按照医嘱服用药物，如有不适请及时就医。',
                '请严格按照说明书或医生建议的剂量服用。',
                '药物使用需要根据个人情况调整，建议咨询专业医生。'
            ]
            return replies[Math.floor(Math.random() * replies.length)]
        }

        if (message.includes('症状') || message.includes('不舒服') || message.includes('疼痛')) {
            const replies = [
                '建议您详细描述症状，以便我更好地为您分析。',
                '如果症状持续或加重，请及时就医检查。',
                '请保持休息，多喝水，观察症状变化。'
            ]
            return replies[Math.floor(Math.random() * replies.length)]
        }

        if (message.includes('谢谢') || message.includes('感谢')) {
            const replies = [
                '不客气，很高兴能帮助到您。',
                '不用谢，这是我应该做的。',
                '希望我的建议对您有帮助！'
            ]
            return replies[Math.floor(Math.random() * replies.length)]
        }

        if (message.includes('你好') || message.includes('您好')) {
            const replies = [
                '您好！我是您的健康顾问，有什么可以帮助您的吗？',
                '您好！请描述一下您的问题，我会尽力为您解答。',
                '您好！很高兴为您服务，请告诉我您的健康问题。'
            ]
            return replies[Math.floor(Math.random() * replies.length)]
        }

        // 默认回复
        const defaultReplies = [
            '感谢您的咨询，我会认真分析您的问题。',
            '这是一个很好的问题，让我为您详细解答。',
            '我理解您的担忧，请放心，我会尽力帮助您。',
            '根据您的描述，我建议您注意以下几点...',
            '这个问题很重要，建议您咨询专业医生获得更详细的指导。'
        ]
        return defaultReplies[Math.floor(Math.random() * defaultReplies.length)]
    }

    // 发送自动回复
    const sendAutoReply = (userMessage: string) => {
        setTimeout(() => {
            const replyContent = generateAutoReply(userMessage)
            const autoReply: Message = {
                id: Date.now().toString() + '_auto',
                content: replyContent,
                type: 1,
                isUser: false,
                timestamp: new Date().toLocaleTimeString('zh-CN', {
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false
                }),
                avatar: '../../../public/doctor-avatar.png'
            }

            setMessages(prev => [...prev, autoReply])
        }, 1000 + Math.random() * 2000) // 1-3秒延迟
    }

    return (
        <div className="zxun">
            {/* 头部 */}
            <div className="chat-header">
                <LeftOutline className="back-btn" onClick={() => navigate(-1)} />
                <span className="chat-title">{doctorName || '小美'}</span>
                <div className="header-right"></div>
            </div>

            {/* 消息列表 */}
            <div className="chat-messages">
                {messages.map((message) => (
                    <div key={message.id} className={`message-item ${message.isUser ? 'user-message' : 'doctor-message'}`}>
                        <div className="message-avatar">
                            <img src={message.avatar} alt="头像" />
                        </div>
                        <div className="message-content">
                            <div className={`message-bubble ${message.isUser ? 'user-bubble' : 'doctor-bubble'}`}>
                                {message.type === 2 ? (
                                    <img src={message.content} alt="图片" className="message-image" />
                                ) : (
                                    <span className="message-text">{message.content}</span>
                                )}
                            </div>
                            <div className="message-time">{message.timestamp}</div>
                        </div>
                    </div>
                ))}
                <div ref={messagesEndRef} />
            </div>

            {/* 表情面板 */}
            {showEmoji && (
                <div className="emoji-panel">
                    <div className="emoji-grid">
                        {emojis.map((emoji, index) => (
                            <span
                                key={index}
                                className="emoji-item"
                                onClick={() => sendEmoji(emoji)}
                            >
                                {emoji}
                            </span>
                        ))}
                    </div>
                </div>
            )}

            {/* 输入区域 */}
            <div className="chat-input">
                <div className="input-center">
                    <input
                        type="text"
                        value={inputText}
                        onChange={(e) => setInputText(e.target.value)}
                        onKeyPress={(e) => e.key === 'Enter' && sendTextMessage()}
                        placeholder="输入消息..."
                        className="text-input-main"
                    />
                </div>

                <div className="input-right">
                    <div className="input-icon image-icon" onClick={() => fileInputRef.current?.click()}>
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                            <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
                            <circle cx="8.5" cy="8.5" r="1.5" />
                            <polyline points="21,15 16,10 5,21" />
                        </svg>
                    </div>
                    <div className="input-icon" onClick={() => setShowEmoji(!showEmoji)}>
                        😊
                    </div>
                </div>

                {/* 隐藏的文件输入 */}
                <input
                    type="file"
                    ref={fileInputRef}
                    accept="image/*"
                    onChange={handleImageUpload}
                    style={{ display: 'none' }}
                />
            </div>

        </div>
    )
}

export default Zxun